/**
 * 图片图层类
 * 支持在地图上叠加图片
 */

import { Map as OlMap } from 'ol';
import { Image as OlImageLayer } from 'ol/layer';
import { ImageStatic } from 'ol/source';
import { BaseLayer } from './BaseLayer';
import { ImageLayerOptions, Coordinate } from '../types';
import { DataUtil } from '../utils/data';
import { Extent } from 'ol/extent';

/**
 * 图片图层类
 */
export class ImageLayer extends BaseLayer {
  /** 图层配置 */
  protected options: ImageLayerOptions;

  /**
   * 构造函数
   * @param options 图层配置
   */
  constructor(options: ImageLayerOptions) {
    super(options);
    this.options = {
      projection: 'EPSG:3857',
      ...options
    };
  }

  /**
   * 创建图层
   */
  protected createLayer(): void {
    const { url, extent, projection } = this.options;

    // 转换范围为EPSG:3857坐标
    const minCoord = DataUtil.toOlCoordinate([extent[0], extent[1]]);
    const maxCoord = DataUtil.toOlCoordinate([extent[2], extent[3]]);
    const olExtent: Extent = [minCoord[0], minCoord[1], maxCoord[0], maxCoord[1]];

    const source = new ImageStatic({
      url,
      imageExtent: olExtent,
      projection: projection || 'EPSG:3857'
    });

    this.layer = new OlImageLayer({
      source
    });
  }

  /**
   * 更新图片
   * @param url 新的图片URL
   */
  updateImage(url: string): void {
    this.options.url = url;
    if (this.map && this.layer) {
      this.map.removeLayer(this.layer);
      this.createLayer();
      this.applyOptions();
      this.map.addLayer(this.layer);
    }
  }

  /**
   * 更新图片范围
   * @param extent 新的范围
   */
  updateExtent(extent: [number, number, number, number]): void {
    this.options.extent = extent;
    if (this.map && this.layer) {
      this.map.removeLayer(this.layer);
      this.createLayer();
      this.applyOptions();
      this.map.addLayer(this.layer);
    }
  }
}

